package tcpfileupadatedemo3;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

/**
 * Created by L.jp
 * Description:
 * User: 86189
 * Date: 2022-08-09
 * Time: 22:39
 */
//多线程处理文件接收保存到本地，然后返回上传成功到客户端
public class ThreadSocket implements Runnable {
    private final Socket acceptSocket;
    
    public ThreadSocket(Socket accept) {
        this.acceptSocket=accept;
    }
    @Override
    public void run() {
        BufferedOutputStream bos=null;
        try {
            //网络中的流,从客户端读取数据的
            BufferedInputStream bis = new BufferedInputStream(acceptSocket.getInputStream());
            //本地的流，写到本地，永久存储
            //给上传的文件名变成唯一的
             bos = new BufferedOutputStream(new FileOutputStream("src/ServerImg/" + UUID.randomUUID().toString() + ".jpg"));
            //从网络流中读取到本地
            int b;
            while ((b = bis.read()) != -1) {
                //写到本地的输出流
                bos.write(b);
            }
            
            //向客户端发送“上传成功”
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(acceptSocket.getOutputStream()));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(bos!=null) {
                //关闭本地链接
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(acceptSocket!=null) {
                try {
                    acceptSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
